// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Author: wsfuyibing <682805@qq.com>
// Date: 2025-04-02

package table

type (
	// Row
	// 单元行.
	Row interface {
		Add(cells ...Cell) Row
		GetCell(index int) Cell
		GetCells() []Cell
		GetWidth(index int) int
		GetWidths() map[int]int
		Iterate(iterator RowIterator) Row
	}

	// RowIterator
	// 单元行遍历.
	RowIterator func(index int, cell Cell)

	row struct {
		length int
		width  map[int]int
		cells  []Cell
	}
)

// NewRow
// 创建单元行.
func NewRow() Row {
	return &row{
		cells: make([]Cell, 0),
		width: make(map[int]int),
	}
}

// +---------------------------------------------------------------------------+
// | Interface methods                                                         |
// +---------------------------------------------------------------------------+

func (o *row) Add(cells ...Cell) Row {
	o.cells = append(o.cells, cells...)
	o.length = len(o.cells)

	for i, c := range o.cells {
		if c == nil {
			o.width[i] = 0
		} else {
			o.width[i] = c.GetWidth()
		}
	}
	return o
}

func (o *row) GetCell(index int) Cell {
	if index >= 0 && index < o.length {
		return o.cells[index]
	}
	return nil
}

func (o *row) GetCells() []Cell { return o.cells }

func (o *row) GetWidth(index int) int {
	if index >= 0 && index < o.length {
		return o.width[index]
	}
	return 0
}

func (o *row) GetWidths() map[int]int {
	return o.width
}

func (o *row) Iterate(iterator RowIterator) Row {
	for i, c := range o.cells {
		iterator(i, c)
	}
	return o
}
